<?php

namespace App\Console\Commands;

use App\Document;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class StaticFileCacheCommand extends Command
{
    /**
     * The name and signature of the console command.
     * 静态文件从第三方缓存到本地
     * @var string
     */
    protected $signature = 'static-file {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $action = $this->argument('action');

        if ($action === 'pull') {
            //静态文件拉取到本地缓存
            $this->pull();
        } elseif ($action === 'push') {
            //静态文件推送到文件服务器存储
            $this->push();
        } else {

            echo "错误--------------------\n";
        }
    }

    //静态文件拉取到本地缓存
    protected function pull()
    {

        echo "文件拉取到本地完成--------------------\n";
    }

    //静态文件推送到文件服务器存储
    protected function push()
    {

        echo "文件推送完成--------------------\n";
    }

    protected function moveDocumentTo($to = 'uploads')
    {
        $storage = Storage::disk(config('admin.upload.disk'));
        Document::query()->get()->map(function ($model) use ($storage, $to) {
            $path = $model['path'];
            if ($storage->exists($path)) {
                $content = $storage->get($path);
                $path = sprintf('%s/%s.%s',
                    $to,
                    \Illuminate\Support\Str::random(40),
                    path_info($model['name'], PATHINFO_EXTENSION)
                );
                $storage->put($path, $content);
                $model->path = $path;
                $model->save();
                echo $model['name'] . "  ok--------------- \n";
            }
        });
    }
}
